package com.wwwarehouse.usercenter.tools;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.usercenter.R;

import java.util.ArrayList;
import java.util.List;


/**
 * @author : mundane
 * @description : 我自己专用的, 别的人不要动
 */

public class FlowLayout extends ViewGroup {
	private final String TAG = "FlowLayout";
	// 最后一个tag, 显示数量
	private TextView mTvLast;
	// 倒数第二个View, 显示省略号
	private TextView mTvLastSecond;
	private int mTagCount = 0;
	private int mTvLastWidth;
	private int mTvLastSecondWidth;
	private int mTvLastMeasuredWidth;
	private int mTvLastSecondMeasuredWidth;
	// 预排列
	private boolean mIsPreViewLayout = true;

	public void setLastTagCount(int tagCount) {
		mTagCount = tagCount;
		mTvLast.setText(String.format("%d个", mTagCount));
	}

	public FlowLayout(Context context) {
		this(context, null);
	}

	public FlowLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initData(context);
	}

	private void initData(Context context) {
		mTvLast = (TextView) LayoutInflater.from(context).inflate(R.layout.layout_tv_tag, this, false);
		mTvLastSecond = (TextView) LayoutInflater.from(context).inflate(R.layout.layout_tv_tag, this, false);
		mTvLastSecond.setText("......");
	}

	@Override
	public void addView(View child) {
		super.addView(child);
	}

	private int lastIndex;
	private int lastSecondIndex;

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);

		int maxRowWidth = 0; // 最大的行宽
		int totalRowHeight = 0; // 累加的所有行的高度

		int currentRowTotalWidth = 0; // 累计每一行的子View宽度之和
		int currentRowMaxHeight = 0; // 当前行最大的高度

		int leftMargin = 0;
		int rightMargin = 0;
		int rowCount = 0;
		int childCount = getChildCount();
		for (int i = 0; i < childCount; i++) {
			View child = getChildAt(i);
			measureChild(child, widthMeasureSpec, heightMeasureSpec); // 测量子View的宽和高
			MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
			leftMargin = lp.leftMargin;
			rightMargin = lp.rightMargin;
			int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin; // 子View占据的宽度
			int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin; // 子View占据的高度
			if (getPaddingLeft() + currentRowTotalWidth + childWidth + getPaddingRight() < parentWidth) { // 未换行, 累加行宽
				currentRowTotalWidth += childWidth; // 叠加行宽
				currentRowMaxHeight = Math.max(currentRowMaxHeight, childHeight); // 得到当前行最大的高度
			} else { // 换行
				if (mIsPreViewLayout) {
					rowCount += 1;
					if (rowCount == 6) {
						LogUtils.showInfoLog("i = " + i);
						View lastChild = getChildAt(i - 1);
						if (lastChild instanceof TextView) {
							((TextView) lastChild).setText(String.format("%d个", mTagCount));
						}
						View lastSecondChild = getChildAt(i - 2);
						if (lastSecondChild instanceof TextView) {
							((TextView) lastSecondChild).setText("......");
						}
						for (int k = i; k < childCount; k++) {
							View otherChild = getChildAt(k);
//							if (otherChild instanceof TextView) {
//								((TextView) otherChild).setText(null);
//							}
							otherChild.setVisibility(GONE);
						}
						mIsPreViewLayout = false;
						requestLayout();

					}
				}

				maxRowWidth = Math.max(maxRowWidth, currentRowTotalWidth); // 对比得到最大的宽度
				currentRowTotalWidth = childWidth; // 重置lineWidth
				totalRowHeight += currentRowMaxHeight; // 累加行高
				currentRowMaxHeight = childHeight;
			}
			//	因为每次换行的时候, height加的是上一行的高度, 所以到最后一行的时候, 要加上最后一行的高度
			//	比如说, 只有一行的时候, 没有换行, 于是就不会走else里面的逻辑, 所以totalRowHeight等于0, 所以要加上最后一行的高度
			if (i == childCount - 1) { // 最后一个控件
				maxRowWidth = Math.max(maxRowWidth, currentRowTotalWidth);
				totalRowHeight += currentRowMaxHeight;
			}
		}
		mTvLastSecond.measure(0, 0);
		mTvLastSecondWidth = mTvLastSecond.getMeasuredWidth() + leftMargin + rightMargin;
		mTvLastSecondMeasuredWidth = mTvLastSecond.getMeasuredWidth();
		mTvLast.measure(0, 0);
		mTvLastWidth = mTvLast.getMeasuredWidth() + leftMargin + rightMargin;
		mTvLastMeasuredWidth = mTvLast.getMeasuredWidth();
		LogUtils.showInfoLog("mTvLastSecondWidth = " + mTvLastSecondWidth + ", mTvLastWidth = " + mTvLastWidth);
		int measuredWidth = widthMode == MeasureSpec.EXACTLY ? parentWidth : maxRowWidth + getPaddingLeft() + getPaddingRight();
		int measuredHeight = heightMode == MeasureSpec.EXACTLY ? parentHeight : totalRowHeight + getPaddingTop() + getPaddingBottom();
		setMeasuredDimension(measuredWidth, measuredHeight);
	}

	private int mRemainWidth;

	//	储存所有行的View的集合
	private List<List<View>> mAllViewList = new ArrayList<>();
	//	储存所有行的高度
	private List<Integer> mRowHeightList = new ArrayList<>();

	private final int MAX_ROW = 6;

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		mAllViewList.clear();
		mRowHeightList.clear();

		int parentWidth = getWidth();
		int currentRowTotalWidth = 0; // 当前行之前累计的行的宽度
		int currentRowMaxHeight = 0; // 当前行的最大高度
		List<View> currentRowViewList = new ArrayList<>();
		int childCount = getChildCount();
		for (int i = 0; i < childCount; i++) {
			View childView = getChildAt(i);
			MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
			int childWidth = childView.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
			int childHeight = childView.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

			if (getPaddingLeft() + currentRowTotalWidth + childWidth + getPaddingRight() < parentWidth) { // 不需要换行
				currentRowViewList.add(childView);
				currentRowTotalWidth += childWidth;
				currentRowMaxHeight = Math.max(currentRowMaxHeight, childHeight);
			} else { // 如果需要换行
				mAllViewList.add(currentRowViewList);
				mRowHeightList.add(currentRowMaxHeight);
				currentRowTotalWidth = childWidth;
				currentRowMaxHeight = childHeight;
				currentRowViewList = new ArrayList<>();
				currentRowViewList.add(childView);
			}
			if (i == childCount - 1) { // 如果是最后一个了
				mAllViewList.add(currentRowViewList);
				mRowHeightList.add(currentRowMaxHeight);
			}
		}
		//	都表示行数, 所以两者应该相等
		LogUtils.showInfoLog("mAllViewList.size() = " + mAllViewList.size() + ", allHeights.size() = " + mRowHeightList.size());
		// 设置子View的位置
		int paddingLeft = getPaddingLeft();
		int paddingTop = getPaddingTop();
		// 行数
		int rowCount = mAllViewList.size();
		//最多显示6行
		if (rowCount > MAX_ROW) {
			rowCount = MAX_ROW;
		}
		for (int i = 0; i < rowCount; i++) {
			// 当前行的所有的View
			currentRowViewList = mAllViewList.get(i);
			currentRowMaxHeight = mRowHeightList.get(i);
			for (int j = 0; j < currentRowViewList.size(); j++) {
				View child = currentRowViewList.get(j);
				// 判断child的状态
				if (child.getVisibility() == View.GONE) {
					continue;
				}
				MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
				int left = paddingLeft + lp.leftMargin;
				int top = paddingTop + lp.topMargin;
				int right = left + child.getMeasuredWidth();
				int bottom = top + child.getMeasuredHeight();
				// 为子View进行布局
				child.layout(left, top, right, bottom);
				paddingLeft += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
			}
			// 换行了
			paddingLeft = getPaddingLeft();
			paddingTop += currentRowMaxHeight;
		}
	}

	private int calculateCurrentRowTotalWidth(List<View> currentRowViewList) {
		int width = getPaddingLeft();
		for (int i = 0; i < currentRowViewList.size(); i++) {
			View child = currentRowViewList.get(i);
			// 判断child的状态
			if (child.getVisibility() == View.GONE) {
				continue;
			}
			MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
			width += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
		}
		return width;
	}

	private int getBreakIndex(List<View> currentRowViewList, int paddingLeft) {
		for (int i = 0; i < currentRowViewList.size(); i++) {
			View child = currentRowViewList.get(i);
			// 判断child的状态
			if (child.getVisibility() == View.GONE) {
				continue;
			}
			MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
			paddingLeft += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
			// 假如超过了边界, 返回该索引
			if (paddingLeft > mRemainWidth) {
				return i;
			}
		}
		return 0;
	}

	/**
	 * 与当前ViewGroup对应的LayoutParams
	 */
	@Override
	public LayoutParams generateLayoutParams(AttributeSet attrs) {
		return new MarginLayoutParams(getContext(), attrs);
	}
}
